package pers.wang.toolset.coder.util.date;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.function.Consumer;

public class DateUtil {
	/**
	 * 获取一天的最大时间
	 * @param date
	 * @return
	 */
	public static Date getEndOfDay(Date date) {
	    LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());;
	    LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
	    return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
	}
	public static Long getEndOfDayMillis(Date date) {
		return getEndOfDay(date).getTime();
	}
	/**
	 * 获取一天的最小时间
	 * @param date
	 * @return
	 */
	public static Date getStartOfDay(Date date) {
	    LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
	    LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
	    return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
	}
	/**
	 * 获取两个日期之间的相差天数，格式为yyyy-MM-dd
	 * @param beginDate
	 * @param endDate
	 * @return
	 * @throws ParseException
	 */
	public static int differs(String beginDate,String endDate) throws ParseException {
		DateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date bDate=sdf.parse(beginDate);
        Date eDate=sdf.parse(endDate);
        Long days=(eDate.getTime()-bDate.getTime())/(1000*3600*24);
        return days.intValue();
	}
	public static void workingBetween(String beginDate,String endDate,Consumer<Date> working) throws ParseException {
		int days = differs(beginDate, endDate);
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		Date bDate=sdf.parse(beginDate);
		for(int i = 0; i <= days; i++) {
			c.setTime(bDate);
			c.add(Calendar.DAY_OF_MONTH, i); 
			working.accept(c.getTime());
		}
	}
	
	public static void main(String[] args) throws Exception {
		DateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		DateUtil.workingBetween("2018-11-05", "2019-12-31", (date) -> {
			String s = sdf.format(date);
			System.out.println("create table if not exists `customer_flow_detail_"+s+"` like `customer_flow_detail` ; ");
		});
	}
}
